package com.huang.msmservice.controller;

import com.huang.msmservice.service.Msmservice;
import com.huang.msmservice.utils.RandomUtil;
import com.hunag.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("eudmsm/msm")
public class MsmController {

    @Autowired
    private Msmservice msmservice;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信方式
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis获取验证码  如果获取到直接发送
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //如果获取不到  进行阿里云发送
        //生成一个随机值 传递给阿里云 他来发送
        code = RandomUtil.getFourBitRandom();
        System.out.println(code);

        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        Boolean isSend = msmservice.sendMsm(map, phone);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES); //发送成功  把验证码放入redis  设置有效时间
            return R.ok().message("发送成功");
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
